﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class UIPlayerManager : MonoBehaviour {

	public CharacterType characterType;
	public UILabel playerName;
	public UILabel cardLeft;
	public UILabel point;
	public GameObject cardRoot;

	public void CreateCards(List<Card> cards)
	{
		int depth = 1;
		foreach(Card card in cards)
		{
//			if (!card.isSprite)
//			{
				GameObject obj = Resources.Load("poker") as GameObject;
				GameObject poker = NGUITools.AddChild(cardRoot, obj);
				CardSprite sprite = poker.gameObject.GetComponent<CardSprite>();
				sprite.Poker = card;
				sprite.Select = false;
				sprite.SetDepth (depth ++);
//			}
		}
		cardRoot.GetComponent<UIGrid> ().Reposition ();
	}

	public void CreateCards()
	{
		if(characterType == CharacterType.Desk)
		{
			DeskCardsCache.Instance.Sort ();
			CreateCards (DeskCardsCache.Instance.Cards);
			return;
		}
		HandCards hand = GetComponent<HandCards> ();
		hand.Sort ();
		CreateCards (hand.Cards);
	}

	public void RemoveCards(Card[] removedCards)
	{
		Transform cardRootTrans = cardRoot.transform;
		for(int index = cardRootTrans.childCount - 1; index > 0; index -- )
		{
			Transform child = cardRootTrans.GetChild (index);
			CardSprite childSprite = child.GetComponent<CardSprite> ();
			foreach(Card removedCard in removedCards)
			{
				if (childSprite.Poker.GetCardName == removedCard.GetCardName) 
				{
					GameObject.DestroyImmediate (child.gameObject);
					break;
				}
			}
		}
		cardRoot.GetComponent<UIGrid> ().Reposition ();
	}

	public void UpdateCards()
	{
		Clear ();
		CreateCards ();
	}

	public void Clear()
	{
		cardRoot.transform.DestroyChildren ();
	}

	public List<Card> SelectedCard
	{
		get{ 
			List<Card> selected = new List<Card> ();
			Transform cardRootTrans = cardRoot.transform;
			for (int index = cardRootTrans.childCount - 1; index > 0; index--) 
			{
				Transform child = cardRootTrans.GetChild (index);
				CardSprite childSprite = child.GetComponent<CardSprite> ();
				if(childSprite.Select)
				{
					selected.Add (childSprite.Poker);
				}
			}
			return selected;
		}
	}
}
